<script setup lang="ts">
import { onMounted, onUnmounted, Ref, ref, shallowRef, watch } from 'vue'
import * as monaco from 'monaco-editor'
import { getCodeSuggestions } from '@/api/code/codeCompletion';

// const editor = defineModel("editor") as Ref<monaco.editor.IStandaloneCodeEditor>;
const codeEditBox = ref<HTMLElement | null>(null);
// const content = defineModel("content") as Ref<string>;
const content = defineModel("content") as Ref<string>;
const options = ref({} as monaco.editor.IStandaloneEditorConstructionOptions);
// let editor = {} as monaco.editor.IStandaloneCodeEditor;
const editor = shallowRef({} as monaco.editor.IStandaloneCodeEditor);
const loading = ref(false);

onMounted(() => {
    init();
})

const init = () => {
    monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
        noSemanticValidation: true,
        noSyntaxValidation: false
    })
    monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
        target: monaco.languages.typescript.ScriptTarget.ES2020,
        allowNonTsExtensions: true
    })
    options.value.value = content.value;
    options.value.wordWrap = 'on';
    options.value.language = 'sql';
    options.value.theme = 'vs-dark';
    options.value.automaticLayout = true;
    options.value.suggest = {
        snippetsPreventQuickSuggestions: false,
        showWords: true,
        showKeywords: true
    }
    if (codeEditBox.value != null) {
        editor.value = monaco.editor.create(codeEditBox.value, options.value)
    }
    editor.value.onDidChangeModelContent(() => {
        const now = editor.value.getValue();
        content.value = now;
    })
    // 注册AI补全提供者
    handleEditorMount();
}
// 销毁编辑器
onUnmounted(() => {
    if (editor.value) {
        editor.value.dispose();
    }
});

const handleEditorMount = () => {
    // 注册补全建议提供者
    monaco.languages.registerCompletionItemProvider('sql', {
        triggerCharacters: [' ', '.', ',', '('],
        async provideCompletionItems(model, position) {
            loading.value = true;
            const trigger = new Set([' ', '.', ',', '(']);
            try {
                const code = model.getLineContent(position.lineNumber);
                console.log("code: ", code);
                const wordPos = new monaco.Position(position.lineNumber, position.column);
                const wordInfo = model.getWordUntilPosition(wordPos);
                const suggestions = await fetchAISuggestions(code);
                // console.log("wordInfo: ", wordInfo);
                return {
                    suggestions: suggestions.map((suggestion: { text: string; }) => ({
                        label: suggestion.text,
                        kind: monaco.languages.CompletionItemKind.Function,
                        insertText: suggestion.text,
                        detail: 'AI 建议',
                        range: new monaco.Range(
                            position.lineNumber,
                            wordInfo.startColumn,
                            position.lineNumber,
                            wordInfo.endColumn
                        )
                    }))
                };
            } finally {
                loading.value = false;
            }
        }
    });
};

// AI接口
const fetchAISuggestions = async (codeContent: string) => {
    const response = await getCodeSuggestions(codeContent);
    const data = await response;
    const dataList = data.substring(3, data.length - 3)
        .split('\n')
        .filter((item) => {
            return item.trim().length !== 0 && item.indexOf('sql') === -1
        })
    console.log('response-data:', data, 'datalist:', dataList,);
    return dataList.map((c) => ({ label: c, text: c }));
};
</script>

<template>
    <div ref="codeEditBox" class="codeEditBox">
        <div v-if="loading" class="loading-indicator">AI正在思考...</div>
    </div>
</template>

<style lang="scss" scoped>
.codeEditBox {
    width: 100%;
    height: 100%;
}

.loading-indicator {
    position: absolute;
    top: 50px;
    right: 5px;
    z-index: 1000;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 12px;
}
</style>